import React, { useEffect, useState } from 'react';
import Taro, { getNFCAdapter, useDidShow } from '@tarojs/taro';
import TitleBar from '@/src/components/titleBar';
import { View } from '@tarojs/components';
import { AtTabs, AtTabsPane } from 'taro-ui';
import store from '@/src/store';
import './index.less';
import { observer } from 'mobx-react-lite';
import { collectionListFun } from '@/src/common/method/userInfoFun';
import CommentItem from '@/src/components/commentItem';
import ArticleItem from '@/src/components/articleItem';
import VedioItem from '@/src/components/vedioItem';
import InfiniteScroll from '@/src/components/infiniteScroll';
import CommonBlank from '@/src/components/pageBlank';
import { getNetWorkStatus } from '@/src/common/util/util';
import { netWorkErrorInfo } from '@/src/utils/constants';
//内容收藏
const mineCollect = () => {
  const pageNum = 10;
  const [current, setCurrent] = useState(0);
  const [dataList, setDataList] = useState<any>([]);
  const [loadingText, setLoadingText] = useState<any>('加载中');
  const ucUserId: any = Taro.getStorageSync('userId');
  const ucLoginPhone: any = Taro.getStorageSync('mobile');
  const [maxPageNum, setMaxPageNum] = useState<number>(0);
  const [pageIndex, setPageIndex] = useState<number>(1);
  const [dynamicList, setDynamicList] = useState([]); //动态数据
  const [articleList, setArticleList] = useState([]); //文章数据
  const [videoList, setVideoList] = useState([]); //视频数据
  const [contentType, setContentType] = useState<any>('ALL');
  // 一级下拉刷新状态
  const [refresherTriggered, setRefresherTriggered] = useState(false);
  const tabList: any = [
    { title: '全部', value: 'ALL' },
    { title: '动态', value: 'DYNAMIC' },
    { title: '文章', value: 'ARTICLE' },
    { title: '视频', value: 'VIDEO' },
  ];
  useDidShow(() => {
    getCollectionList(pageIndex, contentType);
    Taro.onNetworkStatusChange(getNetWorkStatus);
  });
  //获取收藏列表
  const getCollectionList = (pageIndex: any, contentType: any) => {
    collectionListFun({
      ucUserId: ucUserId,
      ucLoginPhone: ucLoginPhone,
      contentKind: 'CIGAR',
      contentType: contentType,
      pageSize: pageNum,
      pageNum: pageIndex,
    }).then((res: any) => {
      setLoadingText('');
      if (res && res.totalCount > 0) {
        setMaxPageNum(Math.ceil(res.totalCount / pageNum));
        let result: any = [];
        if (pageIndex === 1) {
          result = [...res.list];
        } else {
          result = [...dataList, ...res.list];
        }

        const processed =
          result &&
          result.map((item: any) => ({
            ...item,
            select: false,
          }));
        //根据contentType分类
        let dynamic: any = [];
        let article: any = [];
        let video: any = [];
        processed.forEach((item: any) => {
          if (item.contentType === 'DYNAMIC') {
            dynamic.push(item);
          }
          if (item.contentType === 'ARTICLE') {
            article.push(item);
          }
          if (item.contentType === 'VIDEO') {
            video.push(item);
          }
        });
        console.log(article, '==========');
        setDynamicList(dynamic);
        setArticleList(article);
        setVideoList(video);

        setDataList(processed);
      } else {
        setDataList([]);
      }
    });
  };
  //下拉查询数据
  const onEndReached = () => {
    if (loadingText === '加载中') {
      return false;
    }
    const index = pageIndex + 1;
    if (index > maxPageNum) {
      return false;
    }
    setPageIndex(index);
    setLoadingText('加载中...');
    return getCollectionList(index, contentType);
  };
  //加载下一页
  const loadMore = () => {
    let val: any = false;
    if (loadingText === '' && onEndReached) {
      setLoadingText('加载中...');
      val = onEndReached();
    }
  };
  useEffect(() => {
    getCollectionList(pageIndex, contentType);
  }, []);
  //跳转到详情
  const gotoDetail = (item: any, name: any) => {
    if (!store.commonStore.networkStatus) {
      Taro.showToast({ title: netWorkErrorInfo, icon: 'none' });
      return;
    }
    if (name === 'userCenter') {
      Taro.navigateTo({
        url: `/subPagesAccount/userCenter/index?contentKind=${item.contentKind}&&contentType=${item.contentType}&&userId=${item.userInfoVo.ucUserId}`,
      });
    } else if (name === 'comment') {
      Taro.navigateTo({
        url: `/subPagesAccount/commentDetail/index?contentId=${item.contentId}&&contentKind=${item.contentKind}&&contentType=${item.contentType}`,
      });
    } else if (name === 'article') {
      Taro.navigateTo({
        url: `/subPagesAccount/articleDetail/index?contentId=${item.contentId}&&contentKind=${item.contentKind}&&contentType=${item.contentType}`,
      });
    } else {
      Taro.navigateTo({
        url: `/subPagesAccount/vedioDetail/index?contentId=${item.contentId}&&contentKind=${item.contentKind}&&from=mine&&contentType=${item.contentType}`,
      });
    }
  };

  const contentList = () => {
    // 按当前 tab 过滤出“可见列表”
    const visible = (dataList || []).filter((item: any) => {
      if (!item?.title) return false;
      if (current === 0) return true;
      if (current === 1) return item.contentType === 'DYNAMIC';
      if (current === 2) return item.contentType === 'ARTICLE';
      if (current === 3) return item.contentType === 'VIDEO';
      return false;
    });

    return (
      <View>
        {visible.map((item: any, index: number) => (
          <View key={`${item.contentType}-${index}`}>
            {item.contentType === 'DYNAMIC' &&
              (current === 0 || current === 1) && (
                <CommentItem mine={false} data={item} gotoDetail={gotoDetail} />
              )}
            {item.contentType === 'ARTICLE' &&
              (current === 0 || current === 2) && (
                <ArticleItem
                  mine={false}
                  data={item}
                  home
                  gotoDetail={gotoDetail}
                />
              )}
            {item.contentType === 'VIDEO' &&
              (current === 0 || current === 3) && (
                <VedioItem mine={false} data={item} gotoDetail={gotoDetail} />
              )}
          </View>
        ))}

        {/* 只在“当前过滤结果为空”且“非加载中”时渲染空态 */}
        {loadingText === '' && visible.length === 0 && (
          <CommonBlank desc="暂无收藏内容" visible />
        )}
      </View>
    );
  };
  const handleTabClick = (index: any) => {
    if (!store.commonStore.networkStatus) {
      Taro.showToast({ title: netWorkErrorInfo, icon: 'none' });
      return;
    }
    setCurrent(index);
    setContentType(tabList[index].value);
    setPageIndex(1);
    getCollectionList(1, tabList[index].value);
  };

  // 一级下拉刷新处理
  const handleRefreshFun = () => {
    if (!store.commonStore.networkStatus) {
      Taro.showToast({ title: netWorkErrorInfo, icon: 'none' });
      return;
    }
    setLoadingText('加载中...');
    setRefresherTriggered(true);
    //是否是首次下拉刷新
    getCollectionList(pageIndex, contentType);
    setTimeout(() => {
      setRefresherTriggered(false);
    }, 1000);
  };
  // 顶部
  const { windowHeight, screenWidth } = Taro.getSystemInfoSync();
  const rpx2px = (rpx: number) => (rpx / 750) * screenWidth;
  const contentPx =
    windowHeight -
    rpx2px(store.commonStore.safeAreaTop) -
    store.commonStore.safeAreaBottom;
  return (
    <View
      className={`mine-collect-container mine-collect-container-${store.commonStore.isIos}`}
      style={{
        paddingTop: `${store.commonStore.pageAreaTop}rpx`,
      }}
    >
      <TitleBar title="内容收藏" showLeftBack={true} />
      <View className="mine-collect-content">
        {/* 头部导航 */}
        <View className="mine-collect-content-header">
          <AtTabs
            tabList={tabList}
            current={current}
            swipeable={false}
            animated={false}
            className="common-tab"
            onClick={(index) => handleTabClick(index)}
          >
            {/* 全部 */}
            <AtTabsPane current={current} index={0}>
              <InfiniteScroll
                style={{ height: `${contentPx}px` }}
                hasMore={pageIndex < maxPageNum}
                loadMore={() => loadMore()}
                handleRefresh={() => handleRefreshFun()}
                refresherTriggered={refresherTriggered}
                dataList={dataList}
                loading={loadingText === '' ? false : true}
                content={contentList()}
              />
            </AtTabsPane>
            {/* 动态 */}
            <AtTabsPane current={current} index={1}>
              <InfiniteScroll
                style={{ height: `${contentPx}px` }}
                hasMore={pageIndex < maxPageNum}
                loadMore={() => loadMore()}
                handleRefresh={() => handleRefreshFun()}
                refresherTriggered={refresherTriggered}
                dataList={dataList}
                loading={loadingText === '' ? false : true}
                content={contentList()}
              />
            </AtTabsPane>
            {/* 文章 */}
            <AtTabsPane current={current} index={2}>
              <InfiniteScroll
                style={{ height: `${contentPx}px` }}
                hasMore={pageIndex < maxPageNum}
                loadMore={() => loadMore()}
                dataList={dataList}
                handleRefresh={() => handleRefreshFun()}
                refresherTriggered={refresherTriggered}
                loading={loadingText === '' ? false : true}
                content={contentList()}
              />
            </AtTabsPane>
            {/* 视频 */}
            <AtTabsPane current={current} index={3}>
              <InfiniteScroll
                style={{ height: `${contentPx}px` }}
                hasMore={pageIndex < maxPageNum}
                loadMore={() => loadMore()}
                handleRefresh={() => handleRefreshFun()}
                refresherTriggered={refresherTriggered}
                dataList={dataList}
                loading={loadingText === '' ? false : true}
                content={contentList()}
              />
            </AtTabsPane>
          </AtTabs>
        </View>
      </View>
    </View>
  );
};

export default observer(mineCollect);
